
import { defineAsyncComponent, ref } from 'vue';

let agentPortStart = 30308;
let agentPortEnd = 30318;
let checkingPort = 30308;
const agentUrl = 'https://openblock.localhost.lionscript.online';
let state = ref('offline');// scanning, online, offline
let agentVersion = ref(0);

class Agent {
    getStateRef() {
        return state;
    }
    getState() {
        return state.value;
    }
    getVersionRef() {
        return agentVersion;
    }
    getVersion() {
        return agentVersion.value;
    }
    async scan() {
        if (state.value != 'offline') return;
        state.value = 'scanning';
        checkingPort = agentPortStart;
        while (true) {
            try {
                const url = `${agentUrl}:${checkingPort}`;
                let response = await fetch(url)
                if (response.status != 200) {
                    checkingPort++;
                    return;
                }
                let str = await response.text();
                let info = JSON.parse(str);
                if (info.name == 'roar_agent') {
                    agentVersion.value = info.version;
                    state.value = 'online';
                    break;
                }
            } catch (e) {
                // console.log(e);
            }
            checkingPort++;
            if (checkingPort > agentPortEnd) {
                checkingPort = agentPortStart;
            }
        }
    }
    async waitForOnline() {
        while (state.value != 'online') await new Promise(r => setTimeout(r, 100));
    }
    async cmd(file, args) {
        let url = `${agentUrl}:${checkingPort}/cmd/${args?.join('/')}`;
        console.log(url);
        let response = (await axios.post(`${url}`, file)).data;
        console.log(response);
    }
}
export let agent = new Agent();
(async function () {
    while (true) {
        while (state.value == 'offline') {
            await new Promise(r => setTimeout(r, 1000));
        }
        await agent.scan();
        if (state.value == 'offline') continue;
        let url = `${agentUrl}:${checkingPort}/version`;
        try {
            let response = (await axios.post(`${url}`)).data;
            console.log(response);
            let v = parseFloat(response);
            if (agentVersion.value != v) {
                state.value = 'offline';
            } else {
                await new Promise(r => setTimeout(r, 60000));
            }
        } catch (e) {
            state.value = 'offline';
        }
    }
})();